package com.duoduo.homework.h1;

import java.util.ArrayList;
import java.util.List;

import com.duoduo.algs4.util.DrawUtil;

import edu.princeton.cs.algs4.Point2D;
import edu.princeton.cs.algs4.Stopwatch;
import edu.princeton.cs.introcs.StdDraw;
import edu.princeton.cs.introcs.StdOut;
import edu.princeton.cs.introcs.StdRandom;

public class PointInterval {

	private Point2D[] points;
	private List<Point2D[]> shortestPoints;
	private double shortestVal;

	public PointInterval(int N) {
		points = new Point2D[N];
		shortestPoints = new ArrayList<Point2D[]>();
		shortestVal = Double.MAX_VALUE;
		for (int i = 0; i < N; i++) {
			// points[i] = new Point2D(0, i / 1.0 / N);
			points[i] = new Point2D(StdRandom.random(), StdRandom.random());
		
		}
	}

	public void calculateShortestPoint() {
		int N = points.length;
		assert N >= 2;
		double shortVal;
		for (int i = 0; i < N; i++) {
			for (int j = i + 1; j < N; j++) {
				shortVal = points[i].distanceTo(points[j]);
//				StdOut.println(shortVal + " - " + shortestVal);
				if (shortVal > shortestVal) {
					continue;
				} else if (shortVal < shortestVal) {
					shortestVal = shortVal;
					// 小于，则更新原来的最短对儿list
					shortestPoints = new ArrayList<Point2D[]>();
				}
				Point2D[] ps = new Point2D[2];
				ps[0] = points[i];
				ps[1] = points[j];
				shortestPoints.add(ps);
			}
		}
	}

	public void draw() {
		int N = points.length;

		for (int i = 0; i < N; i++) {
			points[i].draw();
		}

		N = shortestPoints.size();
		Point2D[] ps = null;
		StdDraw.setPenColor(StdDraw.RED);
		StdDraw.setPenRadius(.005);
		for (int i = 0; i < N; i++) {
			ps = shortestPoints.get(i);
			ps[0].drawTo(ps[1]);
		}
	}

	public String toString() {
		return String.format("最短距离为%7.5f,共有%d组", shortestVal,shortestPoints.size());
	}
	public void test(){
		this.calculateShortestPoint();
		StdOut.println(this);
	}

	public static void main(String[] args) {
		Stopwatch timer = new Stopwatch();
		PointInterval pi = new PointInterval(2000);
		pi.calculateShortestPoint();
		StdOut.println(timer.elapsedTime());
		pi.draw();
		StdOut.println(pi);

	}

}
